package com.jn.zhinongbao.adapter;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.supportingagriculturaltreasures.bean.Cart;
import com.example.supportingagriculturaltreasures.bean.Order;
import com.example.supportingagriculturaltreasures.bean.Product;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.ChatManager;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;

import java.io.File;

public class ProductDetailActivity extends AppCompatActivity {

    private ImageView ivProductImage;
    private TextView tvProductName, tvProductPrice, tvProductCategory, tvProductLocation;
    private TextView tvShopName, tvMerchantName, tvContactPhone, tvLikes;
    private Button btnAddToCart, btnBuyNow, btnCustomerService, btnCall;
    
    private Product product;
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;
    private ChatManager chatManager;
    private User currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);

        initViews();
        initDatabase();
        loadUserData();
        loadProductData();
        setupClickListeners();
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("商品详情");
        }

        ivProductImage = findViewById(R.id.iv_product_image);
        tvProductName = findViewById(R.id.tv_product_name);
        tvProductPrice = findViewById(R.id.tv_product_price);
        tvProductCategory = findViewById(R.id.tv_product_category);
        tvProductLocation = findViewById(R.id.tv_product_location);
        tvShopName = findViewById(R.id.tv_shop_name);
        tvMerchantName = findViewById(R.id.tv_merchant_name);
        tvContactPhone = findViewById(R.id.tv_contact_phone);
        tvLikes = findViewById(R.id.tv_likes);
        
        btnAddToCart = findViewById(R.id.btn_add_to_cart);
        btnBuyNow = findViewById(R.id.btn_buy_now);
        btnCustomerService = findViewById(R.id.btn_customer_service);
        btnCall = findViewById(R.id.btn_call);
    }

    private void initDatabase() {
        databaseHelper = new DatabaseHelper(this);
        preferenceManager = new PreferenceManager(this);
        chatManager = ChatManager.getInstance(this);
    }

    private void loadUserData() {
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
            if (currentUser == null) {
                Toast.makeText(this, "用户信息获取失败，请重新登录", Toast.LENGTH_LONG).show();
                finish();
            }
        } else {
            Toast.makeText(this, "请先登录", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void loadProductData() {
        Intent intent = getIntent();
        
        // 创建Product对象
        product = new Product();
        product.setId(intent.getIntExtra("product_id", 0));
        product.setName(intent.getStringExtra("product_name"));
        product.setPrice(intent.getDoubleExtra("product_price", 0.0));
        product.setLocation(intent.getStringExtra("product_location"));
        product.setContactPhone(intent.getStringExtra("product_contact_phone"));
        product.setImageUrl(intent.getStringExtra("product_image_url"));
        product.setCategory(intent.getStringExtra("product_category"));
        product.setShopName(intent.getStringExtra("product_shop_name"));
        product.setMerchantName(intent.getStringExtra("product_merchant_name"));
        product.setMerchantId(intent.getIntExtra("product_merchant_id", 0));
        product.setLikes(intent.getIntExtra("product_likes", 0));

        // 显示商品信息
        displayProductInfo();
    }

    private void displayProductInfo() {
        tvProductName.setText(product.getName());
        tvProductPrice.setText(String.format("¥%.2f", product.getPrice()));
        tvProductCategory.setText(product.getCategory());
        tvProductLocation.setText("发货地：" + product.getLocation());
        tvShopName.setText(product.getShopName() != null ? product.getShopName() : "店铺名称");
        tvMerchantName.setText("商家：" + product.getMerchantName());
        tvContactPhone.setText(product.getContactPhone());
        tvLikes.setText(product.getLikes() + "人想要");

        // 加载商品图片
        loadProductImage();
    }

    private void loadProductImage() {
        String imageUrl = product.getImageUrl();
        if (imageUrl == null || imageUrl.isEmpty()) {
            ivProductImage.setImageResource(R.drawable.ic_launcher_foreground);
            return;
        }

        // 判断是文件路径还是content URI
        Object imageSource;
        if (imageUrl.startsWith("/")) {
            // 文件路径
            File imageFile = new File(imageUrl);
            if (imageFile.exists()) {
                imageSource = imageFile;
            } else {
                ivProductImage.setImageResource(R.drawable.ic_launcher_foreground);
                return;
            }
        } else if (imageUrl.startsWith("content://")) {
            // content URI
            imageSource = Uri.parse(imageUrl);
        } else {
            // 其他情况
            imageSource = imageUrl;
        }

        // 使用Glide加载图片
        Glide.with(this)
                .load(imageSource)
                .placeholder(R.drawable.ic_launcher_foreground)
                .error(R.drawable.ic_launcher_foreground)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .centerCrop()
                .into(ivProductImage);
    }

    private void setupClickListeners() {
        // 加入购物车
        btnAddToCart.setOnClickListener(v -> addToCart());

        // 立即购买
        btnBuyNow.setOnClickListener(v -> showBuyNowDialog());

        // 客服
        btnCustomerService.setOnClickListener(v -> startCustomerService());

        // 拨打电话
        btnCall.setOnClickListener(v -> {
            if (product.getContactPhone() != null && !product.getContactPhone().isEmpty()) {
                Intent callIntent = new Intent(Intent.ACTION_DIAL);
                callIntent.setData(Uri.parse("tel:" + product.getContactPhone()));
                startActivity(callIntent);
            } else {
                Toast.makeText(this, "联系电话不可用", Toast.LENGTH_SHORT).show();
            }
        });

        // 点击图片查看大图
        ivProductImage.setOnClickListener(v -> {
            // TODO: 实现图片预览功能
            Toast.makeText(this, "图片预览功能开发中...", Toast.LENGTH_SHORT).show();
        });
    }

    /**
     * 添加商品到购物车
     */
    private void addToCart() {
        if (currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建购物车项
        Cart cart = new Cart(
                currentUser.getId(),
                product.getMerchantId(),
                product.getId(),
                product.getName(),
                product.getPrice(),
                product.getImageUrl(),
                1 // 默认数量为1
        );

        // 添加到购物车
        boolean success = databaseHelper.addToCart(cart);
        if (success) {
            Toast.makeText(this, "已加入购物车", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "加入购物车失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示立即购买对话框
     */
    private void showBuyNowDialog() {
        if (currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("立即购买");
        builder.setMessage("商品：" + product.getName() + "\n价格：¥" + String.format("%.2f", product.getPrice()) + "\n\n确认购买吗？");
        
        builder.setPositiveButton("确认", (dialog, which) -> {
            dialog.dismiss();
            showPaymentPasswordDialog();
        });
        
        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        
        builder.show();
    }

    /**
     * 显示支付密码输入对话框
     */
    private void showPaymentPasswordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("输入支付密码");
        builder.setMessage("请输入6位支付密码：");

        final EditText passwordInput = new EditText(this);
        passwordInput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        passwordInput.setHint("请输入6位数字密码");
        passwordInput.setMaxLines(1);
        
        builder.setView(passwordInput);

        builder.setPositiveButton("确认支付", (dialog, which) -> {
            String password = passwordInput.getText().toString().trim();
            if (validatePaymentPassword(password)) {
                dialog.dismiss();
                processPayment();
            } else {
                Toast.makeText(this, "支付密码格式错误，请输入6位数字", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 验证支付密码格式
     */
    private boolean validatePaymentPassword(String password) {
        return password != null && password.length() == 6 && password.matches("\\d{6}");
    }

    /**
     * 处理支付并创建订单
     */
    private void processPayment() {
        // 模拟支付处理
        Toast.makeText(this, "正在处理支付...", Toast.LENGTH_SHORT).show();

        // 创建订单
        Order order = new Order(
                currentUser.getId(),
                product.getMerchantId(),
                product.getId(),
                product.getName(),
                product.getPrice(),
                product.getImageUrl(),
                1, // 默认数量为1
                "默认收货地址", // 实际应用中应该让用户选择收货地址
                currentUser.getPhone() // 使用用户的电话号码
        );

        // 保存订单到数据库
        boolean success = databaseHelper.addOrder(order);
        if (success) {
            Toast.makeText(this, "支付成功！订单已生成", Toast.LENGTH_LONG).show();
            showOrderSuccessDialog();
        } else {
            Toast.makeText(this, "订单创建失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示订单成功对话框
     */
    private void showOrderSuccessDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("购买成功");
        builder.setMessage("恭喜您成功购买了商品！\n" +
                "商品：" + product.getName() + "\n" +
                "价格：¥" + String.format("%.2f", product.getPrice()) + "\n" +
                "订单状态：已付款\n\n" +
                "商家将尽快为您发货，请注意查收。");
        
        builder.setPositiveButton("确定", (dialog, which) -> {
            dialog.dismiss();
            // 可以选择跳转到订单页面或其他页面
        });
        
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.show();
    }

    /**
     * 启动客服聊天功能
     */
    private void startCustomerService() {
        if (currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (product.getMerchantId() == currentUser.getId()) {
            Toast.makeText(this, "不能与自己聊天", Toast.LENGTH_SHORT).show();  
            return;
        }

        try {
            // 创建或获取聊天室
            String chatRoomId = chatManager.createOrGetChatRoom(currentUser.getId(), product.getMerchantId());
            
            if (chatRoomId != null) {
                // 发送一条初始消息表示对商品感兴趣
                String initialMessage = "您好，我对您的商品「" + product.getName() + "」很感兴趣，请问还有库存吗？";
                boolean messageSent = chatManager.sendMessage(chatRoomId, currentUser.getId(), initialMessage);
                
                // 跳转到聊天界面
                Intent intent = new Intent(this, ChatActivity.class);
                intent.putExtra("chat_room_id", chatRoomId);
                intent.putExtra("other_user_name", product.getMerchantName());
                intent.putExtra("other_user_id", product.getMerchantId());
                startActivity(intent);
                
                if (messageSent) {
                    Toast.makeText(this, "已创建聊天会话", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "创建聊天会话失败，请重试", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "启动客服聊天失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 